<?php

class IndexController extends Zend_Controller_Action 
{
    function init()
    {
        $this->initView();
        Zend_Loader::loadClass('AuxDbTable');
        Zend_Loader::loadClass('Mainmenu');
        Zend_Loader::loadClass('User');
        Zend_Loader::loadClass('Startpage');
        Zend_Loader::loadClass('Project');
        Zend_Loader::loadClass('Task');
        Zend_Loader::loadClass('Card');
        Zend_Loader::loadClass('Rights');
        Zend_Loader::loadClass('Usertasklinks');
        $this->view->baseUrl = $this->_request->getBaseUrl();
        $this->view->user = Zend_Auth::getInstance()->getIdentity();
    }
    
    function preDispatch()
    {
        $auth = Zend_Auth::getInstance();
        if (!$auth->hasIdentity()) {
            $this->_redirect('auth/login');
        }
    }

    function indexAction()
    {
        $menu = new Mainmenu();
        $this->view->main_menu = $menu->getMenu($this->view->user->id);
        
        $this->view->title = "";
        $this->view->content_title = 'Welcome';
        $this->view->flashvars = 'team=1&user_id='.$this->view->user->id.'&start_date='.date('Y-m-d',time()-6*86400).'&end_date='.date('Y-m-d',time());
        $this->view->swf_height = '450';
        $this->view->swf_filename = 'user_report';
        
        $Rights = new Rights();
        $this->view->is_teamrights = $Rights->CanDo($this->view->user->id,'index','teamconfig');
        
        $this->render();
    }
    
    function searchAction()
    {
        $menu = new Mainmenu();
        $this->view->main_menu = $menu->getMenu($this->view->user->id);
        
        $this->view->title = "Search result";
        $this->view->content_title = 'Search result';
        
        Zend_Loader::loadClass('Zend_Filter_StripTags');
        $filter = new Zend_Filter_StripTags();
        
        $key = trim($filter->filter($this->_request->getPost('search_task')));    
        $obj = new Task();
        $result = $obj->fetchAll('LOWER(jira_key)="'.strtolower($key).'"
                                  AND jira_key!=""');
        if(count($result)>0)
        {
            $this->_redirect('/card/index/tid/'.$result[0]->id);
        }
        else
        {
            $this->view->message = "Task [".$key."] wasn't found.";
        }
        $this->render();
    }
    
    function teamconfigAction()
    {
        $Rights = new Rights();
        if(!$Rights->CanDo($this->view->user->id,'index','teamconfig'))$this->_redirect(DEFAUL_URL);
         
        $menu = new Mainmenu();
        $this->view->main_menu = $menu->getMenu($this->view->user->id);
        
        $this->view->content_title = $this->view->title = "Start Page Config";
        
        if (strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
            $team_id = $this->view->user->id;
            $links = new Startpage();
            $links->ClearLinks($team_id);
            
            $users = $this->_request->getParam('users');
            foreach($users as $user_id)
            {
                $links->LinkUser($team_id,$user_id);
            }
            $this->_redirect(DEFAUL_URL);
        } 
        else 
        {
            $id = $this->view->user->id;
            $user = new User();
            $this->view->users = $user->fetchAll('deleted!=1 and id!='.$id,'last_name');
            $this->view->title = $this->view->content_title = $this->view->user->last_name.' '.$this->view->user->first_name.' : Start Page';
            
            $links = new Startpage();
            $r_links = $links->fetchAll('team_id='.$id);
            $this->view->links = array();
            foreach($r_links as $link)
            {
                $this->view->links[] = $link['user_id'];
            }
        }
        
        $this->view->action = 'teamconfig';
        
        $this->render(); 
    }
    
    function selectprojectAction()
    {
        $menu = new Mainmenu();
        $this->view->main_menu = $menu->getMenu($this->view->user->id);
        $this->view->content_title = $this->view->title = "Please select Project";
        
        if(isset($_COOKIE['last_project']))
        {
            $Rights = new Rights();
            if($Rights->CanSeeProject($this->view->user->id,$_COOKIE['last_project'])) $this->_redirect('/index/timeadd/pid/'.$_COOKIE['last_project'].'/tid/'.$_COOKIE['last_task'].'/');
        }
        
        $obj = new Project();
        $uid = $this->view->user->id;
        
        if (strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
            $project = $this->_request->getParam('pid');
            if($project>0 && $obj->fetchRow('id='.$project))
            {
               $this->_redirect('/index/timeadd/pid/'.$project);
            }
        } 
        
        $this->view->projects = $obj->getMyProjects($uid,'0');
        $this->view->buttonText = 'Continue';
        $this->view->action = 'selectproject';
        
        $this->render(); 
    }
    
    function timeaddAction()
    {
        if(!isset($_SESSION['mytasks_only'])) $_SESSION['mytasks_only']=' checked ';
        $projObj = new Project();
        $pid = $this->_request->getParam('pid');
        $projRow = $projObj->fetchRow('id='.$pid);
        if(!$pid || !$projRow)
        {
            $this->_redirect('/index/selectproject');
        }
        
        $MyTasks = new Usertasklinks();
        
        $Rights = new Rights();
        if(!$Rights->CanSeeProject($this->view->user->id,$pid)) $this->_redirect('/index/selectproject');
        
        $menu = new Mainmenu();
        $this->view->main_menu = $menu->getMenu($this->view->user->id);
        $this->view->content_title = $this->view->title = "Add timecard to ".$projRow->name;
        $this->view->pid = $pid;
        $this->view->project_name = $projRow->name;
        $this->view->project_prefix = $projRow->prefix;
        $this->view->next = (int)$this->_request->getParam('next');
        
        Zend_Loader::loadClass('Zend_Filter_StripTags');
        $filter = new Zend_Filter_StripTags();
        
        $task_id = (int)$this->_request->getParam('tid');    
        $jira_key = trim($filter->filter($this->_request->getPost('jira_key')));
        $title = trim($filter->filter($this->_request->getPost('task_summary')));
        $tdate = trim($filter->filter($this->_request->getPost('tdate')));
        $date_pattern = '/^[0-9]{4}\-(?:0[1-9]|1[0-2])\-[1-9]$/'; 
        if(preg_match($date_pattern,$tdate))
        {
            list($y,$m,$d)=explode('-',$tdate);
            $tdate = $y.'-'.$m.'-0'.$d;
        }
        $time = trim($filter->filter($this->_request->getPost('time')));
        $comment = trim($filter->filter($this->_request->getPost('comment')));
        
        $project_prefix = trim($filter->filter($this->_request->getPost('project_prefix')));
        $generate = trim($filter->filter($this->_request->getPost('auto_key')));
                
        if(!$task_id && strtolower($_SERVER['REQUEST_METHOD']) == 'post')
        {
            $taskObj = new Task();
            $data = array(
                'jira_key' => $jira_key,
                'title' => $title,
                'project_id'  => (int)$pid,
                'date_start'  => date('Y-m-d'),
                'created' => $this->view->user->id,
                'modified' => $this->view->user->id
            );
            
            if($task_id = $taskObj->insertTask($data,$project_prefix,$generate?true:false)) {
                if(!$MyTasks->checkExist($task_id,$this->view->user->id)) $MyTasks->LinkUser($task_id,$this->view->user->id);
            } else {
                $this->view->message = $taskObj->__validationMessage;
            }

            if(isset($_POST['mytasks_only'])) $_SESSION['mytasks_only'] = ' checked ';
            else $_SESSION['mytasks_only'] = '';
        }
        if($task_id && strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
            
            if(isset($_POST['mytasks_only'])) $_SESSION['mytasks_only'] = ' checked ';
            else $_SESSION['mytasks_only'] = '';
            
            $user_id = $this->view->user->id;
            $modified = $this->view->user->id;
            $created = $this->view->user->id;
    
            $data = array(
                'tdate' => $tdate,
                'time' => $time,
                'comment' => $comment,
                'task_id' => $task_id,
                'user_id'  => $user_id,
                'created' => $created,
                'modified' => $modified
            );
            $card = new Card();
            
            if($tdate == '2010-03-08' || $tdate == '2010-03-8' || $tdate == '2010-3-8')
            {
                $this->view->message .= '8 марта выходной. С прошедшим!';
            }
            else 
            {
                if($card->insertCard($data)) {
                    if(!$MyTasks->checkExist($task_id,$this->view->user->id)) $MyTasks->LinkUser($task_id,$this->view->user->id);
                    switch($this->_request->getPost('next'))
                    {
                        case '2': //Close the task.
                            $taskObj = new Task();
                            $data = array('status'=>'7',
                                          'date_end'=>date('Y-m-d'));
                            $taskObj->update($data,'id='.$task_id);
                            $_SESSION['userMessage'] = 'Timecard added successfully.<br>Task closed.';
                            $this->_redirect('/index/timeadd/pid/'.$pid.'/next/'.$this->_request->getPost('next'));
                        break;
                        case '3': //Go to home page
                            $this->_redirect(DEFAUL_URL); 
                        break;
                        default : // add timecard to the same task
                            $_SESSION['userMessage'] = 'Timecard added successfully.';
                            $this->_redirect('/index/timeadd/pid/'.$pid.'/tid/'.$task_id.'/next/'.$this->_request->getPost('next'));
                        break;
                    }
                    
                }else
                {
                    $this->view->message .= $card->__validationMessage;
                }
            }
        } 
        else $tdate = $this->_request->getParam('tdate');
        
        $taskObj = new Task();
        $all_tasks = $taskObj->fetchAll('project_id='.$pid.' and status IN (0)',array('jira_key','title'));
        
        $this->view->tasks = array();
        
        $this->view->my_tasks = $MyTasks->getMyTasksForTheProject($pid,$this->view->user->id);
        
        $cookie_correct = false;
        
        foreach($all_tasks as $t)
        {
            if($_SESSION['mytasks_only'] && !in_array($t->id,$this->view->my_tasks)) continue;
            if($t->id==VACATION_TASK_ID) continue;
            if(@$_COOKIE['last_task']==$t->id)$cookie_correct = true;
            $this->view->tasks[] = $t;
        }
        
        if($task_id>0) $this->view->task_id = $task_id;
        elseif(isset($_COOKIE['last_task']) && $cookie_correct){
            $this->view->task_id = $_COOKIE['last_task'];
        }elseif(count($this->view->tasks)>0){
            $this->view->task_id = $this->view->tasks[0]->id;
        }
        $this->view->tdate = isset($tdate) && strlen($tdate)>0?$tdate:date('Y-m-d');
        $this->view->time = isset($time)&&strlen($time)>0?$time:'';
        $this->view->comment = isset($comment)&&strlen($comment)>0?$comment:'';
        $this->view->jira_key = isset($jira_key)?$jira_key:$project_prefix.'-';
        $this->view->task_summary = isset($title)?$title:'';
        
        $card = new Card();
        $this->view->calendar = $card->MyCalendar($this->view->user->id);
        
        $this->view->action = 'timeadd';
        $this->view->buttonText = 'Add';
        
        $this->render(); 
    }
    
    function quickdeleteAction()
    {
        $menu = new Mainmenu();
        $this->view->main_menu = $menu->getMenu($this->view->user->id);
        
        $this->view->title = "Delete Timecards";
        $this->view->content_title = 'Delete Timecards';
        
        $card = new Card();
        $this->view->calendar = $card->CalendarForDeleting($this->view->user->id);
        
        $this->render();
    }
    
    function deletetimecardAction()
    {
        $menu = new Mainmenu();
        $this->view->main_menu = $menu->getMenu($this->view->user->id);
        
        $this->view->title = "Delete Timecard";
        
        $card = new Card();
        if (strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
            Zend_Loader::loadClass('Zend_Filter_Alpha');
            $filter = new Zend_Filter_Alpha();
            
            $id = (int)$this->_request->getPost('id');
            if(!$card->CanSeeCard($id,$this->view->user->id)) $this->_redirect('/project');
            
            $del = $filter->filter($this->_request->getPost('del'));
            $tid = $filter->filter($this->_request->getPost('tid'));
            
            
            
            if ($del == 'Yes' && $id > 0) {
                $where = 'id = ' . $id;
                $rows_affected = $card->delete($where);
            }
            $this->_redirect('/index/quickdelete');
        } else {
            $id = (int)$this->_request->getParam('id');
            if ($id > 0) {
                // only render if we have an id and can find the task.
                if(!$card->CanSeeCard($id,$this->view->user->id)) $this->_redirect('/index/quickdelete');
                $this->view->card = $card->fetchRow('id='.$id);
                $this->view->tid = $this->view->card->task_id;;
                
                $task = new Task();
                $this->view->task = $task->fetchRow('id='.$this->view->tid);
                
                $project = new Project();
                $this->view->project = $project->fetchRow('id='.$this->view->task->project_id);
    
                $this->view->content_title = $this->view->project->name.' : Task "'.$this->view->task->title.'" : Delete timecard #'.$this->view->card->id;
            
                if ($this->view->task->id > 0) {
                    $this->render();
                    return;
                }
            }
            else
            {
                $this->_redirect('/index/quickdelete');
                return;
            }
        }
        
        // redirect back to the task list unless we have rendered the view
           $this->_redirect('/project/index');
    }
}